use derive_builder::Builder;
use serde::{Deserialize, Serialize};

use crate::error::Error;
use crate::mapper::ValueMapper;
use crate::modeling::{
    Class, ClassAttributeBuilder, ClassBuilder, ClassGetter, ClassRelationBuilder,
    RelationRelatedType, ValueType,
};
use crate::modeling::{
    ClassAttributePersistence, ClassPersistence, ClassPersistenceBuilder, ClassPersistenceGetter,
    ClassRelation, ClassRelationGetter, Value,
};

use super::{FormSchema, ModelProvider};

const MODEL_PROVIDER_SETTING_CLASS_IDENTIFIER: &'static str = "g01_model_provider_setting";

const MODEL_PROVIDER_SETTING_CLASS_NAME: &'static str = "model_provider_setting";

const MODEL_PROVIDER_SETTING_TABLE_NAME: &'static str = "_g01_meta_model_provider_setting";

#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
#[builder(name = "ModelProviderSettingBuilder")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option), default)]
#[builder(derive(Debug))]
#[builder(build_fn(error = "Error"))]
pub struct ModelProviderSetting {
    /// id
    pub id: i64,
    ///
    pub provider_identifier: String,
    ///
    pub is_valid: bool,
    ///
    pub configurate_methods: String,
    ///
    pub system_configuration: String,
    /// encrypted_config
    pub encrypted_config: String,
    /// 上次使用
    pub last_used: i64,
    /// quota_type
    pub quota_type: Option<String>,
    /// quota_limit
    pub quota_limit: i64,
    /// quota_used
    pub quota_used: i64,
    /// 备注
    pub description: Option<String>,
    /// 创建时间
    pub created_at: i64,
    /// 更新时间
    pub updated_at: i64,

    pub credential_schema: Option<FormSchema>,
}

impl ValueMapper for ModelProviderSetting {}
//
crate::impl_from_value!(ModelProviderSetting);
crate::impl_class_persistence_getter!(ModelProviderSetting, MODEL_PROVIDER_SETTING_TABLE_NAME);
crate::impl_class_relations_getter!(
    ModelProviderSetting,
    vec![ClassRelationBuilder::default()
        .src_identifier(ModelProvider::get_identifier()?)
        .target_identifier(Self::get_identifier()?)
        .related_type(RelationRelatedType::Keys)
        .related_at("provider_identifier")
        .build()?]
);

impl ClassGetter for ModelProviderSetting {
    fn get_name() -> anyhow::Result<String> {
        Ok(String::from(MODEL_PROVIDER_SETTING_CLASS_NAME))
    }
    fn get_identifier() -> anyhow::Result<String> {
        Ok(String::from(MODEL_PROVIDER_SETTING_CLASS_IDENTIFIER))
    }
    fn get_class() -> anyhow::Result<Class> {
        let mut attribute_builder = ClassAttributeBuilder::default();
        attribute_builder.class_identifier(MODEL_PROVIDER_SETTING_CLASS_IDENTIFIER);

        let mut commons = crate::modeling::simple_attributes_with_builder(&attribute_builder)?;
        let mut append = vec![
            attribute_builder
                .clone()
                .name("provider_identifier")
                .title("供应商")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("is_valid")
                .title("是否有效")
                .data_type(ValueType::Boolean)
                .build()?,
            attribute_builder
                .clone()
                .name("configurate_methods")
                .title("配置方法")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("system_configuration")
                .title("系统配置")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("encrypted_config")
                .title("配置")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("last_used")
                .title("最近使用")
                .data_type(ValueType::Number)
                .build()?,
            attribute_builder
                .clone()
                .name("quota_type")
                .title("配额类型")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("quota_limit")
                .title("限制")
                .data_type(ValueType::Number)
                .build()?,
            attribute_builder
                .clone()
                .name("quota_used")
                .title("使用")
                .data_type(ValueType::Number)
                .build()?,
        ];
        append.append(&mut commons);
        append.sort_by(|a, b| a.position.cmp(&b.position));

        let clazz = ClassBuilder::default()
            .identifier(MODEL_PROVIDER_SETTING_CLASS_IDENTIFIER)
            .name(MODEL_PROVIDER_SETTING_CLASS_NAME)
            .data_is_type(false)
            .is_persistent(true)
            .primary_key(String::from("identifier"))
            .attributes(append)
            .build()?;
        Ok(clazz)
    }
}
